package com.pi.pro.xcmg.am.was.fac.service;

import com.pi.config.LicenseProperties;
import com.pi.pro.xcmg.am.common.XcmgEncryptionSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


@Slf4j
@Service
public class LicenseService {

    @Autowired
    private LicenseProperties licenseProperties;
    
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 从加密文件加载并解密授权信息
     */
    public void loadFromEncryptedFile() throws Exception {

        this.info("//==LicService:A01");
        String filePath = licenseProperties.getFilePath();
        if (filePath == null || filePath.isEmpty()) {
            throw new IllegalArgumentException("授权文件路径未配置");
        }

        this.info("//==LicService:A02");
        // 读取加密文件
        Resource resource = resourceLoader.getResource("file:" + filePath);
        if (!resource.exists()) {
            throw new IllegalArgumentException("授权文件不存在: " + filePath);
        }

        this.info("//==LicService:A03");
        File file = resource.getFile();
        String encryptedContent = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);

        this.info("//==LicService:A04");
        //this.info("//==key:"+XcmgEncryptionSupport.key());
        // 解密内容
        String decryptedContent = XcmgEncryptionSupport.decrypt(encryptedContent);
        //String decryptedContent = XcmgEncryptionSupport.desDecrypt(encryptedContent);
        //this.info("//==decryptedContent,"+decryptedContent);

        this.info("//==LicService:A05");
        // 解析解密后的属性
        Properties props = new Properties();
        props.load(new java.io.ByteArrayInputStream(decryptedContent.getBytes(StandardCharsets.UTF_8)));

        this.info("//==LicService:A06");
        licenseProperties.setKey(props.getProperty("license.key"));
        licenseProperties.setExpiryDate(props.getProperty("license.expiryDate"));
    }

    /**
     * 验证授权密钥的有效性
     */
    public boolean validateLicense() {
        // 验证密钥是否存在
        if (licenseProperties.getKey() == null || licenseProperties.getKey().trim().isEmpty()) {
            return false;
        }
        
        // 验证密钥格式 (可以根据实际需求自定义)
        if (!isValidKeyFormat(licenseProperties.getKey())) {
            return false;
        }
        
        // 验证有效期
        return isLicenseNotExpired(licenseProperties.getExpiryDate());
    }
    
    /**
     * 验证密钥格式
     */
    public boolean isValidKeyFormat(String key) {
        // 示例: 验证密钥长度和格式
        return key.length() == 16 && key.matches("^[A-Za-z0-9]+$");
    }
    
    /**
     * 验证密钥是否未过期
     */
    public boolean isLicenseNotExpired(String expiryDate) {
        if (expiryDate == null || expiryDate.trim().isEmpty()) {
            return false;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date expiry = sdf.parse(expiryDate+" 20:00:00");
            Date now = new Date();
            
            // 允许有一天的误差，避免时区问题
            return now.before(expiry) || now.equals(expiry);
        } catch (ParseException e) {
            return false;
        }
    }

    private void info(String text){
        if (text==null){
            return;
        }
        if (!XcmgEncryptionSupport.tracing){
            return;
        }
        log.info(text);
    }
}
    